package io.renren.modules.job.task;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.text.StrFormatter;
import io.renren.modules.app.entity.WxKafKaMsg;
import io.renren.modules.app.entity.ibps.BpmApproval;
import io.renren.modules.app.entity.ibps.Employee;
import io.renren.modules.app.entity.ibps.RoleParty;
import io.renren.modules.app.entity.ibps.UserRole;
import io.renren.modules.app.service.IBpmApprovalService;
import io.renren.modules.app.service.IBpmInstService;
import io.renren.modules.app.service.IBpmTasksService;
import io.renren.modules.app.service.IEmployeeService;
import io.renren.modules.app.service.IPartyEntityService;
import io.renren.modules.app.service.IRoleService;
import io.renren.modules.app.service.IUserRoleService;
import lombok.Data;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;

/**
 * 智慧校园推送
 * 
 * @author Administrator
 *
 */
@Slf4j
@Component
public class ZhxyTask {
	@Autowired
	private IBpmApprovalService approyalService;
	@Autowired
	private IBpmInstService instService;
	@Autowired
	private IBpmTasksService taskService;
	@Autowired
	private IEmployeeService employeeService;
	@Autowired
	private IPartyEntityService partEntityService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IUserRoleService roleUserService;

	@Value("${ibpsUrl}")
	private String urlBase;

	@Autowired
	private KafkaTemplate<String, String> kafkaTemplate;

	@Synchronized
	@Scheduled(fixedDelay = 1000 * 3)
	public void main() {
//		ZhxyApp zhxyApp = new ZhxyApp(openAppId, appSecre, objectId, objType);
		// "Process_3fu3lvo" 收文
		// "Process_3bcvksq" // 发文
		Arrays.asList("Process_3fu3lvo", "Process_3bcvksq").forEach(liuchengStr -> {// "Process_3fu3lvo",
			// 1. 查询
			instService.findByDefKey(liuchengStr).forEach(BpmInst -> {
				// 2.查询该流程的正在处于的节点
				Optional.ofNullable(taskService.findByInst(BpmInst.getId())).orElse(Collections.emptyList()).forEach(task -> {
					// 3.查询该节点需要push多少人
					BpmApproval approyal = approyalService.findByTask(task.getId());
					Optional.ofNullable(approyal).ifPresent(approval -> {
						if (!approval.getPush()) {
							List<Push> push = JSONObject.parseArray(approval.getQualfieds(), Push.class);
							System.out.println(push);
							push.forEach(p -> {
								this.getNeedPushEmployee(p).forEach(employee -> {
									log.info("推送人员:{},openId:{}" + employee.getName(), employee.getWcAccount());
									Optional.of(employee).map(Employee::getWcAccount).ifPresent(wcAccount -> {
//										WxMpService mpService = WxMpConfiguration.getMpServices().get("wx7a917b3b518e0deb");
										// <br />您有新的工作流需要审批<a
										// href="http://localhost:8080/ibps-platform-admin/platform/bpmn/bpmTask/toStart.htm?id=565098472613609472">管理员在2019-04-01
										// 17:04:17发起协和收文</a>
										String html = "审批提醒：<br />您有新的工作流需要审批<a href=\"{}/platform/bpmn/bpmTask/toStart.htm?id={}\">{}</a>";
										html = StrFormatter.format(html, urlBase, task.getId(), task.getSubject());
//										WxMpKefuMessage msg = WxMpKefuMessage.TEXT().toUser(wcAccount).content(html).build();
//										try {
//											boolean sendKefuMessage = mpService.getKefuService().sendKefuMessage(msg);
//											System.out.println("推送:" + sendKefuMessage);
//										} catch (WxErrorException e) {
//											e.printStackTrace();
//										}
										// 进行推送
										log.info("查询要employee推送:{}", employee);
										WxKafKaMsg wxKafKaMsg = new WxKafKaMsg();
										wxKafKaMsg.setAppId("wx7a917b3b518e0deb").setContent(html).setOpenId(wcAccount);
										
										this.kafkaTemplate.send("test", JSONObject.toJSONString(wxKafKaMsg));
									});
								});
							});
							approyalService.save(approval.setPush(true));// 标注已经推送过了
						} else {
							log.info("已经推送过了");
						}
					});
				});
			});
		});
	}

	// 获取要推送信息的员工
	private List<Employee> getNeedPushEmployee(Push p) {
		List<Employee> es = new ArrayList<Employee>();
		if (p.getType() == Type.employee) {
			employeeService.findById(p.getId()).ifPresent(employee -> {
				es.add(employee);
			});
		} else if (p.getType() == Type.party) {
			partEntityService.findById(p.getId()).ifPresent(part -> {
				// 参与者类型。org=；employee=员工；position=岗位 ,role=角色
				String party_type_ = part.getParty_type_();
				switch (party_type_) {
				case "org": {

					break;
				}
				case "position": {
					break;
				}
				case "role": {
					RoleParty role = roleService.findByRoleAlias(part.getParty_alias_());
					List<UserRole> userRoles = roleUserService.findByRoleId(role.getId());
					userRoles.forEach(ur -> {
						employeeService.findById(ur.getUserId()).ifPresent(employee -> {
							es.add(employee);
						});
					});
					break;
				}
				default:
					break;
				}
			});
		}
		return es;
	}

	@Data
	public static class Push {
		private Long id;
		private Type type;
	}

	public enum Type {
		employee, party
	}
}
